package dragon.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.concurrent.ConcurrentHashMap;

import static org.springframework.http.HttpHeaders.AUTHORIZATION;

@Component
public class AuthenSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    ClientDetailsService clientDetailsService;

//    @Autowired
//    AuthorizationServerTokenServices authorizationServerTokenServices;

    @Autowired
    ObjectMapper objectMapper;

    public static final String AUTHENTICATION_SCHEME_BASIC = "Basic";

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication) throws IOException, ServletException {

    }

    /**
     * 账号密码认证成功后，获取头部的Authentication，生成token
     * @param httpServletRequest
     * @param httpServletResponse
     * @param authentication
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        //整个流程及下面用到的，new的类，可以参考有道笔记中，Spring Oauth2的3.1那张流程图。按照我的理解，这个流程是先判断账号密码，再来处理client
        UsernamePasswordAuthenticationToken convert = convert(httpServletRequest);
        String clientId = convert.getPrincipal().toString();
        String clientSecret = convert.getCredentials().toString();
        ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);
        if(clientDetails == null){
            throw new ServletException("clientId不存在");
        }else if(!StringUtils.equals(clientSecret,clientDetails.getClientSecret())){
            throw new ServletException("clientSecret不匹配");
        }
        TokenRequest tokenRequest = new TokenRequest(new ConcurrentHashMap<>(8), clientId, clientDetails.getScope(), "custom");
        OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails);
        OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);
//        OAuth2AccessToken accessToken = authorizationServerTokenServices.createAccessToken(oAuth2Authentication);
        httpServletResponse.setContentType("application/json;charset=UTF-8");
//        httpServletResponse.getWriter().write(objectMapper.writeValueAsString(accessToken));
    }

    /**
     * 解析request头部的Authorization，从中获取clientId和clientSecret
     * 此段代码来源于BasicAuthenticationFilter的doFilterInternal方法
     * @param request
     * @return
     * @throws ServletException
     */
    public UsernamePasswordAuthenticationToken convert(HttpServletRequest request) throws ServletException {
        String header = request.getHeader(AUTHORIZATION);
        if (header == null) {
            throw new ServletException("header没有Authorization");
        }

        header = header.trim();
        if (!StringUtils.startsWithIgnoreCase(header, AUTHENTICATION_SCHEME_BASIC)) {
            throw new ServletException("header的Authorization，其加密方式不为Basic");
        }

        byte[] base64Token = header.substring(6).getBytes(StandardCharsets.UTF_8);
        byte[] decoded;
        try {
            decoded = Base64.getDecoder().decode(base64Token);
        }
        catch (IllegalArgumentException e) {
            throw new BadCredentialsException(
                    "Failed to decode basic authentication token");
        }

        String token = new String(decoded, StandardCharsets.UTF_8);

        int delim = token.indexOf(":");

        if (delim == -1) {
            throw new BadCredentialsException("Invalid basic authentication token");
        }
        UsernamePasswordAuthenticationToken result  = new UsernamePasswordAuthenticationToken(token.substring(0, delim), token.substring(delim + 1));
//        result.setDetails(this.authenticationDetailsSource.buildDetails(request));
        return result;
    }
}
